/**
 * 地块绘制工具
 */
import Base from "./Base";
import MapCommon from "../../common/MapCommon";
import _ from "lodash"



export default class SelectPolygon extends Base {
  /**
   *
   * @param map
   * @param callBack 点选回调
   * @param errorCallBack 错误回调
   * @param clickLayers 点选图层
   * @param features 需要展示到点选图层的要素
   * @param clickLayersFilters 点击图层过滤器
   * @param stopLayers 遮挡图层名字
   */
  constructor(map,{callBack:callBack,errorCallBack:errorCallBack,clickLayers:clickLayers,features=[],clickLayersFilters=[],stopLayers=[],otherLayers=[]}) {
    super(map,'SelectPolygon',{callBack:callBack,errorCallBack:errorCallBack});
    this.clickLayers=[];//点击查询的图层

    if(stopLayers){
      clickLayers=clickLayers.concat(clickLayers)
    }
    for (let i = 0; i <clickLayers.length ; i++) {
      MapCommon.copyLineToAreaFit(this.map,clickLayers[i],clickLayers[i]+"_select");
      this.clickLayers.push(clickLayers[i]+"_select");
    }
    //初始化已选择要素
    this.selectSet={
      "type": "FeatureCollection",
      "features": features||[]

    };//已选择要素集
    this.mode = 'multi';//多选模式
    this.tempLayerName="selectionSetDraw";
    this.clickLayersFilters=clickLayersFilters;
    this.stopLayers=stopLayers;
    this.otherLayers=otherLayers.map(item=>{
      return [item[0]+"_select",item[1]+"_select"]
    });//当两个图层同时出现在点击位置时，禁止点选
  }

  start() {
    super.start();
    //将所有点击线图层转化为面图层
    //增加高亮图层
    if (!this.map.getSource(this.tempLayerName)) {
      this.map.addSource(this.tempLayerName, {
        "type": "geojson",
        "data": this.selectSet
      });
    }
    //添加选择集图层
    if (!this.map.getLayer(this.tempLayerName)) {
      this.map.addLayer({
        id: this.tempLayerName,
        source: this.tempLayerName,
        "minzoom": 7,
        "maxzoom": 18,
        type: 'line',
        "paint": {
          "line-color": "#fffe21",
          "line-opacity": 1,
          "line-width": 6
        },
      });
    }
    this.clickEvent=(e)=>{
      this.select([e.originalEvent.layerX, e.originalEvent.layerY])
    }

    //添加点击事件
    this.map.on('click', this.clickEvent);
  }

  /**
   * 通过点查询用户点击的面要素
   * @param point
   */
  select(point){
    if(this.clickLayers.length===0){
      return;
    }
    let renderFeatures = this.map.queryRenderedFeatures(point, {layers: this.clickLayers});
    if(!renderFeatures||renderFeatures.length===0){
      return;
    }

    //确定优先选中的要素
    let priorityRenderF = this.getPriorityRenderFeature(renderFeatures);
    if(!priorityRenderF||priorityRenderF.length===0){
      return;
    }
    //避免地块被切片分割的问题
    let features = this.map.querySourceFeatures(priorityRenderF.layer.source, {'sourceLayer': priorityRenderF.layer.source, 'filter': ['==', 'objectid', priorityRenderF.properties.objectid]});
    let temp = MapCommon.unionFeatures(features);
    temp.properties=priorityRenderF.properties;
    temp.source=priorityRenderF.source;
    temp.sourceLayer=priorityRenderF.sourceLayer;
    temp.layer=priorityRenderF.layer;

    priorityRenderF=temp;
    priorityRenderF.properties.myobjectid=priorityRenderF.source+priorityRenderF.properties.objectid;
    // 判断正选反选
    let anti_index = this.isAnti_Election(priorityRenderF);
    if(anti_index < 0 && this.selectSet.features && this.selectSet.features.length>=20){
      alert('最多可选择20个地块！');
      return
    }

    this.update(priorityRenderF, anti_index);

  }

  //更新source
  update(feature, anti_index) {
    //反选
    if (anti_index > -1) {
      //选中后,再取消走这
      this.selectSet.features = _.filter(this.selectSet.features, (o) => {
        return o.properties.myobjectid !== feature.properties.myobjectid
      })
    }
    //非反选
    if (anti_index < 0) {
      // 头一次选中-->走这
      this.mode === 'multi' ? this.selectSet.features.push(feature) : this.selectSet.features = [feature]
    }
    if (this.map.getSource('selectionSetDraw')) {
      //  不管第几次选,都会走这
      this.map.getSource('selectionSetDraw').setData(this.selectSet);
    }
    //将每次数据回调
    this.finish(this.selectSet)

  }

  //-1非反选; >-1反选
  isAnti_Election(sourceF) {
    if (!sourceF) {
      return
    }
    let myobjectid = sourceF.properties['myobjectid'];
    let index = _.findIndex(this.selectSet.features, (feature) => {
      return feature.properties.myobjectid === myobjectid
    })
    return index
  }


  //获取优先级高的图层要素
  getPriorityRenderFeature(features) {
    let priority = null;
    //特定图层阻挡下层点击事件
    for (let i = 0; i < this.stopLayers.length; i++) {
      for (let j = 0; j <features.length ; j++) {
        if(this.stopLayers[i]+"_select"==features[j].layer.id){
          return null;
        }
      }
    }
    features=this.filterFeatures(features)
    for (let i = 0; i < this.clickLayers.length; i++) {
      let index = _.findIndex(features, (renderF) => {
        if(renderF.layer.id === this.clickLayers[i]){
          let filters=this.clickLayersFilters.filter(item=>
            (item.layer+"_select")===renderF.layer.id
          );
          if(filters.length===0){
            return true;
          }

          let filter=filters[0];

          if(renderF.properties&&renderF.properties[filter.key]&&renderF.properties[filter.key]==filter.value){
            return false
          }else {
            return true;
          }
        }else {
          return false;
        }
      });

      if (index > -1) {
        priority = JSON.parse(JSON.stringify(features[index]));
        break
      }
    }
    return priority
  }

  /**
   * 如果同时存在遮盖图层，则移除
   * @param features
   */
  filterFeatures(features){
    if(!this.otherLayers||this.otherLayers.length===0){
      return features;
    }
    let ids=features.map(feature=>{
      return feature.layer.id
    })
    let ignoreIds=[];

    for (let i = 0; i < this.otherLayers.length; i++) {
      let item=this.otherLayers[i];

      if((ids.indexOf(item[0])>-1)&&(ids.indexOf(item[1])>-1)){
        ignoreIds=ignoreIds.concat(item)
      }
    }

    return features.filter(feature=>{
      return ignoreIds.indexOf(feature.layer.id)===-1
    })
  }


  close(notClearMap=false) {
    this.clear(notClearMap);
    this.clearEvent();
  }

  clear(notClearMap=false) {
    this.clearMap(notClearMap);
  }

  clearMap(notClearMap=false) {
    //不清除地图选择绘制图层
    if(!notClearMap){
      super.clearMap();
    }

    for (let i = 0; i <this.clickLayers.length ; i++) {
      if (this.map.getLayer(this.clickLayers[i])) {
        this.map.removeLayer(this.clickLayers[i]);
      }
    }

  }

  clearEvent() {
    super.clearEvent();
    this.map.off('click',this.clickEvent);
    this.selectSet={
      "type": "FeatureCollection",
      "features": [
      ]
    };
    this.clickLayers=[];
  }
}
